import { BaseEnvMirror } from "@/modules/dev-env/mirror/mirror.ts";
import { getCustomResourceUrl } from "@/modules/dev-env/common/resource.ts";
import type { ResourceVersionResponse, ToolInstallVersionItem } from "@/modules/dev-env/common/types.ts";
import path from "@/framework/util/path.ts";

export class PgsqlMirror extends BaseEnvMirror {
  constructor() {
    super({
      id: "pgsql.latest",
      name: "最新版",
      url: getCustomResourceUrl("/data/pgsql-windows.json"),
      website: "https://www.postgresql.org/",
    });
  }

  async getDownloadList(query: Record<string, any>): Promise<ToolInstallVersionItem[]> {
    const resp = await native.http.getJson<ResourceVersionResponse>(this.url);
    return resp.data.versions.map(it => {
      // 下载地址: https://get.enterprisedb.com/postgresql/postgresql-16.9-3-windows-x64-binaries.zip
      const filename = path.basename(it.url);
      // 从文件名中提取版本号: 16.9-3,将其转换为16.9.3
      const version = filename.match(/\d+\.\d+(\.\d)?(-\d)?/)?.[0] ?? it.version;
      const installPath = version.replace(/-/g, ".");
      return {
        id: `pgsql-${it.version}`,
        version: it.version,
        name: filename,
        url: it.url,
        installPath: installPath,
        extraToTempdir: true,
      };
    });
  }
}
